﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System;
using STSdb.General.Buffers;

namespace STSdb.Files
{
    internal class Node
    {
        private readonly int[] bits = new int[(int)Math.Ceiling(BRANCH_LENGTH / 32.0)];
        private readonly ulong[] pointers = new ulong[BRANCH_LENGTH];

        public static ushort BRANCH_LENGTH = (ushort)(Sector.SIZE_64 / sizeof(ulong));//8192
        public static readonly int MAX_DEPTH = RawFile.GetDepth(ulong.MaxValue);// 4
        public const ulong INVALID_SECTOR_ID = 0;

        public readonly ulong SectorID;
        public readonly RawFile RawFile;
        public bool IsModified { get; private set; }

        public Node(RawFile rawFile, ulong sectorID)
        {
            if (sectorID == INVALID_SECTOR_ID)
                throw new ArgumentException("Invalid sector.");

            RawFile = rawFile;
            SectorID = sectorID;
            IsModified = false;
        }

        public ulong GetPointer(ushort index)
        {
            return pointers[index];
        }

        public void SetPointer(ushort index, ulong value)
        {
            pointers[index] = value;
            bits.SetBit(index, 1);

            IsModified = true;
        }

        public Node this[ushort index, bool createIfNotExists]
        {
            get
            {
                Node node;
                ulong sectorID = GetPointer(index);
                if (sectorID == INVALID_SECTOR_ID)
                {
                    if (!createIfNotExists)
                        return null;

                    sectorID = RawFile.FileSystem.GetFreeSectorID();
                    SetPointer(index, sectorID);

                    node = new Node(RawFile, sectorID);
                }
                else
                {
                    lock (RawFile.FileSystem.Cache)
                        node = RawFile.FileSystem.Cache.Retrieve(sectorID);

                    if (node != null)
                        return node;

                    node = new Node(RawFile, sectorID);
                    node.Load();
                }

                lock (RawFile.FileSystem.Cache)
                    RawFile.FileSystem.Cache.Packet(node.SectorID, node);

                return node;
            }
        }

        public void Save()
        {
            byte[] buffer = new byte[BRANCH_LENGTH * sizeof(ulong)];
            Buffer.BlockCopy(pointers, 0, buffer, 0, buffer.Length);

            for (int i = 0; i < BRANCH_LENGTH; i++)
            {
                if (bits.GetBit(i) == 1)
                    RawFile.FileSystem.Volume.Write(SectorID * Sector.SIZE_64 + (ulong)(i * sizeof(ulong)), buffer, i * sizeof(ulong), sizeof(ulong));
            }

            for (int i = 0; i < bits.Length; i++)
                bits[i] = 0;

            IsModified = false;
        }

        public void Load()
        {
            byte[] buffer = new byte[BRANCH_LENGTH * sizeof(ulong)];
            RawFile.FileSystem.Volume.Read(SectorID * Sector.SIZE_64, buffer, 0, buffer.Length);
            Buffer.BlockCopy(buffer, 0, pointers, 0, buffer.Length);

            for (int i = 0; i < bits.Length; i++)
                bits[i] = 0;

            IsModified = false;
        }
    }
}
